package com.example.servlet;

import com.example.model.Article;
import com.example.model.User;
import com.example.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/admin-article")
public class AdminArticleServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("user");
        
        // 检查是否是管理员
        if (currentUser == null || !"admin".equals(currentUser.getUsername())) {
            response.sendRedirect("login.jsp");
            return;
        }
        
        try (Connection conn = DBUtil.getConnection()) {
            String sql = "SELECT a.id, a.title, a.content, a.likes, u.username as author_name FROM articles a LEFT JOIN users u ON a.user_id = u.id ORDER BY a.id DESC";
            PreparedStatement stmt = conn.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery();
            
            List<Article> articles = new ArrayList<>();
            while (rs.next()) {
                Article article = new Article();
                article.setId(rs.getInt("id"));
                article.setTitle(rs.getString("title"));
                article.setContent(rs.getString("content"));
                article.setLikes(rs.getInt("likes"));
                article.setAuthorName(rs.getString("author_name"));
                articles.add(article);
            }
            
            request.setAttribute("articles", articles);
            request.getRequestDispatcher("admin-article.jsp").forward(request, response);
            
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("error", "数据库连接错误: " + e.getMessage());
            request.getRequestDispatcher("admin-article.jsp").forward(request, response);
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doGet(request, response);
    }
} 